package com.sapdroid.sapdroiddo;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;

import android.annotation.TargetApi;
import android.app.ActionBar;
import android.app.AlertDialog;
import android.app.LoaderManager;
import android.content.ContentValues;
import android.content.Context;
import android.content.CursorLoader;
import android.content.DialogInterface;
import android.content.Loader;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.app.ListFragment;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.CursorAdapter;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;

import com.sapdroid.sapdroiddo.content.ItemTable;
import com.sapdroid.sapdroiddo.content.KeepDroidContentProvider;
import com.sapdroid.sapdroiddo.content.TodoListTable;

public class MainActivity extends FragmentActivity implements
		ActionBar.OnNavigationListener, LoaderManager.LoaderCallbacks<Cursor> {

	private static final String TAG = "MainActivity";

	public static String ARG_SELECTED_LIST = "SELECTED LIST";

	/**
	 * The {@link android.support.v4.view.PagerAdapter} that will provide
	 * fragments for each of the sections. We use a
	 * {@link android.support.v4.app.FragmentPagerAdapter} derivative, which
	 * will keep every loaded fragment in memory. If this becomes too memory
	 * intensive, it may be best to switch to a
	 * {@link android.support.v4.app.FragmentStatePagerAdapter}.
	 */
	SectionsPagerAdapter mSectionsPagerAdapter;

	/**
	 * The {@link ViewPager} that will host the section contents.
	 */
	ViewPager mViewPager;

	List<HashMap<String, String>> todoLists;
	private List<HashMap<String, String>> datas;

	private int selectedList;

	private ActionBar actionBar;
	private CursorAdapter adapter;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		todoLists = new ArrayList<HashMap<String, String>>();
		HashMap<String, String> def = new HashMap<String, String>();
		def.put(TodoListTable.COLUMN_ID, "0");
		def.put(TodoListTable.COLUMN_DESCRIPTION, "default");
		todoLists.add(def);
		datas = new ArrayList<HashMap<String, String>>();

		// Set up the action bar to show a dropdown list.
		actionBar = getActionBar();
		actionBar.setDisplayShowTitleEnabled(false);
		actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);

		fillData();

		// Create the adapter that will return a fragment for each of the three
		// primary sections of the app.
		mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());

		// Set up the ViewPager with the sections adapter.
		mViewPager = (ViewPager) findViewById(R.id.pager);

	}

	@Override
	protected void onResume() {
		super.onResume();

		mViewPager.setAdapter(mSectionsPagerAdapter);
		mViewPager.setCurrentItem(1);
	}

	private void fillData() {
		getLoaderManager().initLoader(0, null, this);
		adapter = new ActionBarSpinnerCursorAdapter(this, null, true);

		// Set up the dropdown list navigation in the action bar.
		actionBar.setListNavigationCallbacks(adapter, this);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return super.onCreateOptionsMenu(menu);
	}

	@Override
	public boolean onMenuItemSelected(int featureId, MenuItem item) {
		switch (item.getItemId()) {
		case R.id.action_add_item:
			createItem();
			break;
		case R.id.action_add_list:
			createList();
			break;

		case R.id.action_delete_list:
			deleteList();
			break;
		case R.id.action_edit_list:
			// TODO : edit list description
			break;
		case R.id.action_settings:
			// TODO : section dialog
			break;
		default:
			break;
		}
		return true;
	}

	private void deleteList() {
		// delete the list
		int deleted = getContentResolver()
				.delete(KeepDroidContentProvider.CONTENT_URI_LIST, TodoListTable.COLUMN_ID + "=?", new String[] { todoLists
						.get(selectedList).get(TodoListTable.COLUMN_ID) });

		if (deleted == 1) {// delete all items of the list
			getContentResolver()
					.delete(KeepDroidContentProvider.CONTENT_URI_ITEM, ItemTable.COLUMN_LISTID + "=?", new String[] { todoLists
							.get(selectedList).get(TodoListTable.COLUMN_ID) });
		}
	}

	public void updateItem(final HashMap<String, String> itemToUpdate) {
		final LinearLayout layout = new LinearLayout(this);
		layout.setOrientation(LinearLayout.VERTICAL);

		final EditText input = new EditText(this);
		input.setText(itemToUpdate.get(ItemTable.COLUMN_DESCRIPTION));
		layout.addView(input);

		final String id = itemToUpdate.get(ItemTable.COLUMN_ID);

		new AlertDialog.Builder(MainActivity.this)
				.setTitle(R.string.new_todo)
				.setView(layout)
				.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int whichButton) {
						ContentValues values = new ContentValues();
						values.put(ItemTable.COLUMN_DESCRIPTION, input
								.getText().toString());
						values.put(ItemTable.COLUMN_LISTID, todoLists
								.get(selectedList).get(TodoListTable.COLUMN_ID));
						values.put(ItemTable.COLUMN_STATUS, ItemTable.OPEN);

						getContentResolver()
								.update(KeepDroidContentProvider.CONTENT_URI_ITEM, values, ItemTable.COLUMN_ID + "=?", new String[] { id });
						reQuery();
					}
				})
				.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int whichButton) {
						// Do nothing.
					}
				}).show();
	}

	private void createItem() {
		final LinearLayout layout = new LinearLayout(this);
		layout.setOrientation(LinearLayout.VERTICAL);

		final EditText input = new EditText(this);

		layout.addView(input);

		new AlertDialog.Builder(MainActivity.this)
				.setTitle(R.string.new_todo)
				.setView(layout)
				.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int whichButton) {
						ContentValues values = new ContentValues();
						values.put(ItemTable.COLUMN_DESCRIPTION, input
								.getText().toString());
						values.put(ItemTable.COLUMN_LISTID, todoLists
								.get(selectedList).get(TodoListTable.COLUMN_ID));
						values.put(ItemTable.COLUMN_STATUS, ItemTable.OPEN);

						getContentResolver()
								.insert(KeepDroidContentProvider.CONTENT_URI_ITEM, values);
						reQuery();
					}
				})
				.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int whichButton) {
						// Do nothing.
					}
				}).show();
	}

	private void createList() {
		final EditText input = new EditText(this);
		input.setHint(R.string.enter_List_name);
		new AlertDialog.Builder(MainActivity.this)
				.setTitle(R.string.new_todo_list)
				.setView(input)
				.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int whichButton) {
						ContentValues values = new ContentValues();
						values.put(TodoListTable.COLUMN_DESCRIPTION, input
								.getText().toString());

						Uri todoUri = getContentResolver()
								.insert(KeepDroidContentProvider.CONTENT_URI_LIST, values);
						Log.d(TAG, "uri : " + todoUri);
					}
				})
				.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int whichButton) {
						// Do nothing.
					}
				}).show();
	}

	@Override
	protected void onSaveInstanceState(Bundle outState) {
		outState.putInt(ARG_SELECTED_LIST, selectedList);
		super.onSaveInstanceState(outState);
	}

	@Override
	protected void onRestoreInstanceState(Bundle savedInstanceState) {
		super.onRestoreInstanceState(savedInstanceState);
		selectedList = savedInstanceState.getInt(ARG_SELECTED_LIST);

		actionBar.setSelectedNavigationItem(selectedList);
	}

	/**
	 * Backward-compatible version of {@link ActionBar#getThemedContext()} that
	 * simply returns the {@link android.app.Activity} if
	 * <code>getThemedContext</code> is unavailable.
	 */
	@TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
	private Context getActionBarThemedContextCompat() {
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
			return getActionBar().getThemedContext();
		} else {
			return this;
		}
	}

	/**
	 * A {@link FragmentPagerAdapter} that returns a fragment corresponding to
	 * one of the sections/tabs/pages.
	 */
	public class SectionsPagerAdapter extends FragmentPagerAdapter {
		static final String FRAGMENT_TAG = "android:switcher:" + R.id.pager + ":";

		public SectionsPagerAdapter(FragmentManager fm) {
			super(fm);
		}

		@Override
		public Fragment getItem(int position) {
			Fragment fragment = new SectionFragment();
			Bundle args = new Bundle();
			args.putInt(SectionFragment.ARG_SECTION_NUMBER, position);
			fragment.setArguments(args);
			if (todoLists != null && todoLists.size() > 0) {
				((SectionFragment) fragment).setTodoList(todoLists
						.get(selectedList), datas);
			}

			return fragment;
		}

		public void refreshFragments() {
			if (todoLists != null && todoLists.size() > 0) {
				Log.d(TAG, "refreshing fragments!");

				for (int i = 0; i < getCount(); i++) {
					Fragment fragment = getSupportFragmentManager()
							.findFragmentByTag(FRAGMENT_TAG + i);
					if (fragment != null) {
						((SectionFragment) fragment).setTodoList(todoLists
								.get(selectedList), datas);
					}
				}
			}
		}

		@Override
		public int getCount() {
			// Show 3 pages (Open, Done, All).
			return 3;
		}

		@Override
		public CharSequence getPageTitle(int position) {
			Locale l = Locale.getDefault();
			switch (position) {
			case 0:
				return getString(R.string.title_section1).toUpperCase(l);
			case 1:
				return getString(R.string.title_section2).toUpperCase(l);
			case 2:
				return getString(R.string.title_section3).toUpperCase(l);
			}
			return null;
		}
	}

	/**
	 * A fragment representing a section of the app(Open, Done, All)
	 * 
	 */
	public static class SectionFragment extends ListFragment {
		/**
		 * The fragment argument representing the section number for this
		 * fragment.
		 */
		public static final String ARG_SECTION_NUMBER = "section_number";
		private HashMap<String, String> todoList;
		private ListView listView;
		/**
		 * 0 -> Open; 1 -> Done; 2 -> All
		 */
		private int section;
		private TodoItemAdapter listAdapter;
		private List<HashMap<String, String>> itemLists;

		public void setTodoList(HashMap<String, String> todoList, List<HashMap<String, String>> itemLists) {
			this.todoList = todoList;
			this.itemLists = itemLists;
			if (listAdapter != null) {
				listAdapter.setData(itemLists);
			}
		}

		public SectionFragment() {
			todoList = new HashMap<String, String>();
			todoList.put(TodoListTable.COLUMN_ID, "0");
			todoList.put(TodoListTable.COLUMN_DESCRIPTION, "default");
		}

		@Override
		public void onActivityCreated(Bundle savedInstanceState) {
			super.onActivityCreated(savedInstanceState);

			if (listAdapter == null) {
				listAdapter = new TodoItemAdapter(getActivity(), section);
				setListAdapter(listAdapter);
				setTodoList(todoList, itemLists);
			}
		}

		@Override
		public void onSaveInstanceState(Bundle outState) {
			super.onSaveInstanceState(outState);
			outState.putString(TodoListTable.COLUMN_ID, "test");
		}

		@Override
		public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
			View rootView = inflater
					.inflate(R.layout.fragment_main_pager, container, false);

			return rootView;
		}

		@Override
		public void onViewCreated(View view, Bundle savedInstanceState) {
			super.onViewCreated(view, savedInstanceState);
			section = getArguments().getInt(ARG_SECTION_NUMBER);

			if (listAdapter == null) {
				listAdapter = new TodoItemAdapter(getActivity(), section);
				setListAdapter(listAdapter);
			}
			Log.d(TAG, "create new page " + section);
		}
	}

	@Override
	public boolean onNavigationItemSelected(int itemPosition, long itemId) {
		Log.d(TAG, "list : " + itemPosition);

		selectedList = itemPosition;
		reQuery();

		return true;
	}

	public void reQuery() {
		String[] projection = { ItemTable.COLUMN_ID, ItemTable.COLUMN_DESCRIPTION, ItemTable.COLUMN_STATUS };
		String[] selectionAgrs = { todoLists.get(selectedList)
				.get(TodoListTable.COLUMN_ID) };
		Cursor cursor = getContentResolver()
				.query(KeepDroidContentProvider.CONTENT_URI_ITEM, projection, ItemTable.COLUMN_LISTID + " =? ", selectionAgrs, null);
		loadData(cursor);

		mSectionsPagerAdapter.refreshFragments();
	}

	private void loadData(Cursor data) {
		datas.clear();
		for (data.moveToFirst(); !data.isAfterLast(); data.moveToNext()) {
			datas.add(getRow(data));
		}
	}

	private HashMap<String, String> getRow(Cursor cursor) {
		HashMap<String, String> row = new HashMap<String, String>();
		row.put(ItemTable.COLUMN_ID, cursor.getString(cursor
				.getColumnIndex(ItemTable.COLUMN_ID)));
		row.put(ItemTable.COLUMN_DESCRIPTION, cursor.getString(cursor
				.getColumnIndex(ItemTable.COLUMN_DESCRIPTION)));
		row.put(ItemTable.COLUMN_STATUS, cursor.getString(cursor
				.getColumnIndex(ItemTable.COLUMN_STATUS)));
		return row;
	}

	@Override
	public Loader<Cursor> onCreateLoader(int arg0, Bundle arg1) {
		String[] projection = { TodoListTable.COLUMN_ID, TodoListTable.COLUMN_DESCRIPTION };
		CursorLoader cursorLoader = new CursorLoader(this, KeepDroidContentProvider.CONTENT_URI_LIST, projection, null, null, null);
		return cursorLoader;
	}

	@Override
	public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
		adapter.swapCursor(data);

		todoLists.clear();
		for (data.moveToFirst(); !data.isAfterLast(); data.moveToNext()) {
			HashMap<String, String> list = new HashMap<String, String>();
			list.put(TodoListTable.COLUMN_DESCRIPTION, data.getString(data
					.getColumnIndex(TodoListTable.COLUMN_DESCRIPTION)));
			list.put(TodoListTable.COLUMN_ID, data.getString(data
					.getColumnIndex(TodoListTable.COLUMN_ID)));
			todoLists.add(list);
		}
	}

	@Override
	public void onLoaderReset(Loader<Cursor> loader) {
		adapter.swapCursor(null);
	}

}
